import React, { useEffect, useMemo, useState } from 'react'
import style from './index.module.scss'
import logo from '@/assets/home/logo.png'
import { Input } from 'antd'
import { ZoomOutOutlined } from '@ant-design/icons'
import { useNavigate } from 'react-router-dom'
import { addSearchApi, delSearchApi, searchHistoryApi } from '@/common/api'
import { getLs } from '@/common/common'

export default function Header() {
  const [iptFocus,setFocus] = useState(false)
  const [iptValue,setIptValue]=useState('')
  const navigate = useNavigate()
  const [searchList, setSearchList] = useState([])
  const [userId,setUserId] = useState('')
  useEffect(() => {
    if (iptFocus) {
      const { _id } = getLs("userInfo")
      setUserId(_id)
      getSearchHistory(_id);
    }
  }, [iptFocus]);
  const getSearchHistory = async (userId) => {
    
    const RES = await searchHistoryApi({ userId })
    if (RES.code === 200) {
      setSearchList(RES.data)
    }
  }
  const searchApi = async (e) => {
    if(e.key==='Enter'){
      if (iptValue) {
        const RES = await addSearchApi({userId,searchWords:iptValue})
        navigate(`/searchList?key=${iptValue}`)
      }
    }
  }
  const clickSearch = async (e, searchWords) => {
    if (e.target.tagName === 'I') {
      await delSearchApi({userId,searchWords})
      return
    }
     await addSearchApi({userId,searchWords})
    navigate(`/searchList?key=${searchWords}`)
  }
  const delSearch = async () => {
    
  }
  const handleBlur = () => {
    setTimeout(() => setFocus(false), 100); // 延迟隐藏防止点击历史
  }
  return (
    <>
      <div className={style.bigDiv}>
        <div className={style.header}>
          <div className={style.left}>
            <img src={logo} alt="" />
          </div>
          <div className={style.Ipt}>
            <Input 
              onFocus={()=>setFocus(true)}
              onBlur={handleBlur} // 失去焦点时隐藏
              onChange={(e)=>setIptValue(e.target.value)}
              onKeyUp={(e)=>searchApi(e)}
              placeholder='请搜索' />
            <ZoomOutOutlined />
            <ul className={`searchHistory ${iptFocus?'show':""}`}>
              {
                searchList.map(item=>{
                  return <li key={item?._id} onClick={(e) => clickSearch(e,item.searchWords)}>
                    <span>{item.searchWords || "--"}</span>
                    <i>×</i>
                  </li>
                })
                }
            </ul>
          </div>
        </div>
      </div>
    </>
  )
}
